package com.emm.yixun.customer.service.impl.app.manage;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.RoleDataAuthorityService;
import com.emm.yixun.basic.service.SalesGroupService;
import com.emm.yixun.basic.service.SalesGroupUserService;
import com.emm.yixun.basic.service.UserService;
import com.emm.yixun.common.app.GetConsultantListReqDto;
import com.emm.yixun.common.app.GetConsultantListResDto;
import com.emm.yixun.common.app.servletentity.ConsultantListRes;
import com.emm.yixun.common.enums.DataAuthorityEnums;
import com.emm.yixun.common.enums.ResultEnum;
import com.emm.yixun.common.model.RoleDataAuthority;
import com.emm.yixun.common.model.SalesGroup;
import com.emm.yixun.common.model.SalesGroupUser;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.RoleDataAuthorityDto;
import com.emm.yixun.common.model.dto.SalesGroupDto;
import com.emm.yixun.common.model.dto.SalesGroupUserDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.DelFlagEnum;

@Service("getConsultantListManage")
public class GetConsultantListManage {
	@Autowired
	private UserService userService;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private RoleDataAuthorityService roleDataAuthorityService;
	@Autowired
	private SalesGroupUserService salesGroupUserService;
	@Autowired
	private SalesGroupService salesGroupService;
	
	/**
	 * 查询经纪人列表
	 * @param reqDto
	 * @return
	 */
	public GetConsultantListResDto getConsultantList(GetConsultantListReqDto reqDto) {
		GetConsultantListResDto resDto = new GetConsultantListResDto();
		try{
			UserDto userDto = new UserDto();
			List<User> userList = new ArrayList<User>();
			List<ConsultantListRes> consultantList = new ArrayList<ConsultantListRes>();
			resDto.setConsultantList(null);
			/*
			if("0".equals(reqDto.getSearchType())){
				String dataPermission = dataPermissionService.dataPermissionCondition(Long.parseLong(reqDto.getUserId()),
						reqDto.getResourcesCode(), null, null);
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					resDto.setConsultantList(null);
				}else{
					userDto.setDataPermission(dataPermissionArr[1]);
				}
				userList = userService.selectListByDto(userDto);
			}else{
				userList = userService.userByProjectIdForGroup(reqDto.getProjectId());
			}
			*/
			//查询客户的权限。
			//个人：归属人只显示个人
			//销售组：获取销售组下的user
			//项目组：获取项目下的所有销售组钟的user
			//无：不显示
			//全部：显示项目下所有人
			// 2、根据角色,获取用户角色资源权限 sys_tr_role_data_authority
			User user = userService.selectById(Long.valueOf(reqDto.getUserId()));
			//获取用户所在销售组
			SalesGroupUserDto sguDto = new SalesGroupUserDto();
			sguDto.setUserId(user.getId());
			sguDto.setMerchantId(user.getMerchantId());
			sguDto.setAccessCode(reqDto.getProjectCode());
			//status: 状态 0正常 1已关闭
			sguDto.setStatus("0");
			SalesGroupUser sgu = salesGroupUserService.selectByDto(sguDto);
			
			RoleDataAuthorityDto rdahDto = new RoleDataAuthorityDto();
			rdahDto.setResourcesCode("menu_0006_0001");
			rdahDto.setRoleId(user.getRoleId());
			rdahDto.setMerchantId(user.getMerchantId());
			rdahDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
			List<RoleDataAuthority> rdahList = roleDataAuthorityService.selectListByDto(rdahDto);
			if(DataAuthorityEnums.DATA_AUTHORITY_00.getNo().equals(rdahList.get(0).getAuthorityValue())){
				//无权限：反馈空
			}else if(DataAuthorityEnums.DATA_AUTHORITY_01.getNo().equals(rdahList.get(0).getAuthorityValue())){
				//个人权限：反馈自身
				ConsultantListRes clRes = new ConsultantListRes();
				clRes.setConsultantUserId(String.valueOf(user.getId()));
				clRes.setConsultantUserName(user.getUserName());
				consultantList.add(clRes);
				resDto.setConsultantList(consultantList);
			}else if(DataAuthorityEnums.DATA_AUTHORITY_02.getNo().equals(rdahList.get(0).getAuthorityValue())
					|| DataAuthorityEnums.DATA_AUTHORITY_99.getNo().equals(rdahList.get(0).getAuthorityValue())){
				//项目组和全部：暂无此数据权限
				if(null != sgu){
					SalesGroup salesGroup = salesGroupService.selectById(sgu.getSalesGroupId());
					if(null != salesGroup){
						String projectCode = salesGroup.getProjectCode();
						SalesGroupDto sgDto = new SalesGroupDto();
						sgDto.setProjectCode(projectCode);
						sgDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
						List<SalesGroup> sgList = salesGroupService.selectListByDto(sgDto);
						if(null != sgList && sgList.size() > 0){
							StringBuffer sb = new StringBuffer();
							sb.append("AND t.sales_group_id in (");
							for(int ii=0; ii<sgList.size(); ii++){
								SalesGroup sgData = sgList.get(ii);
								sb.append(sgData.getId());
								if(ii == (sgList.size() - 1)){
									sb.append(")");
								}else{
									sb.append(",");
								}
							}
							
							sguDto = new SalesGroupUserDto();
							sguDto.setDataPermission(sb.toString());
							//status: 状态 0正常 1已关闭
							sguDto.setStatus("0");
							List<SalesGroupUser> sguList = salesGroupUserService.selectListByDto(sguDto);
							Set<Long> userSet = new HashSet<Long>(); 
							for(SalesGroupUser sguData: sguList){
								userSet.add(sguData.getUserId());
							}
							if(userSet.size()>0){
								Iterator<Long> it = userSet.iterator();
								sb = new StringBuffer();
								sb.append("AND t.id in (");
								while (it.hasNext()) {
									long str = it.next();
									sb.append(str);
									if(!it.hasNext()){
										sb.append(")");
									}else{
										sb.append(",");
									}
								}
								userDto = new UserDto();
								userDto.setDataPermission(sb.toString());
								userList = userService.selectListByDto(userDto);
								if(userList.size() > 0){
									for(User userData : userList){
										ConsultantListRes clRes = new ConsultantListRes();
										clRes.setConsultantUserId(String.valueOf(userData.getId()));
										clRes.setConsultantUserName(userData.getUserName());
										consultantList.add(clRes);
									}
									resDto.setConsultantList(consultantList);
								}else{
									resDto.setConsultantList(null);
								}
							}
						}
					}
				}
				
			}else if(DataAuthorityEnums.DATA_AUTHORITY_03.getNo().equals(rdahList.get(0).getAuthorityValue())){
				//本部：无本部数据权限
				
			}else if(DataAuthorityEnums.DATA_AUTHORITY_04.getNo().equals(rdahList.get(0).getAuthorityValue())){
				//销售组：反馈会员所在销售组的人员
				if(null != sgu){
					sguDto = new SalesGroupUserDto();
					sguDto.setSalesGroupId(sgu.getSalesGroupId());
					//status: 状态 0正常 1已关闭
					sguDto.setStatus("0");
					List<SalesGroupUser> sguList = salesGroupUserService.selectListByDto(sguDto);
					Set<Long> userSet = new HashSet<Long>(); 
					for(SalesGroupUser sguData: sguList){
						userSet.add(sguData.getUserId());
					}
					if(userSet.size()>0){
						Iterator<Long> it = userSet.iterator();
						StringBuffer sb = new StringBuffer();
						sb.append("AND t.id in (");
						while (it.hasNext()) {
							long str = it.next();
							sb.append(str);
							if(!it.hasNext()){
								sb.append(")");
							}else{
								sb.append(",");
							}
						}
						userDto = new UserDto();
						userDto.setDataPermission(sb.toString());
						userList = userService.selectListByDto(userDto);
						if(userList.size() > 0){
							for(User userData : userList){
								ConsultantListRes clRes = new ConsultantListRes();
								clRes.setConsultantUserId(String.valueOf(userData.getId()));
								clRes.setConsultantUserName(userData.getUserName());
								consultantList.add(clRes);
							}
							resDto.setConsultantList(consultantList);
						}else{
							resDto.setConsultantList(null);
						}
					}
				}
			}

			//归属人：根据登陆用户的数据权限进行反推。此处代码先注释
			//JHSong_2016-10-26_操作:注释
//			userList = userService.userByProjectIdForGroup(reqDto.getProjectId());
//			if(userList.size() > 0){
//				for(User user : userList){
//					ConsultantListRes clRes = new ConsultantListRes();
//					clRes.setConsultantUserId(String.valueOf(user.getId()));
//					clRes.setConsultantUserName(user.getUserName());
//					consultantList.add(clRes);
//				}
//				resDto.setConsultantList(consultantList);
//			}else{
//				resDto.setConsultantList(null);
//			}
			
			resDto.setResult(ResultEnum.SUCCESS.getNo());
		}catch(Exception e){
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("查询经纪人失败!");
			resDto.setResult(ResultEnum.FAILURE.getNo());
			return resDto;
		}
		return resDto;
	}
}
